package org.example;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * @author jack wu
 * @date created by jack wu on 06 12,2023
 * ^^-^^
 */
@Slf4j
@RestController
public class TestController {

    @PostMapping("/cmd")
    public void get(@RequestBody JSONObject object) throws IOException {


        InputStream inputStream = null;
        BufferedReader reader = null;
        List<String> resList = new ArrayList<>();
        try {
            String[] cmdArray = {"/bin/bash", "-c", object.getString("cmd")};
            Process exec = Runtime.getRuntime().exec(cmdArray);
            inputStream = exec.getInputStream();
            reader = new BufferedReader(new InputStreamReader(inputStream));
            String line = null;
            while ((line = reader.readLine()) != null) {
                resList.add(line);
            }
        } catch (Exception e) {
            log.error("error", e);

        } finally {
            IOUtils.closeQuietly(inputStream);
            IOUtils.closeQuietly(reader);
        }

        log.info("res:{}", JSONObject.toJSONString(resList));

    }
}
